package com.example.demomk.Utils;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.ViewModelProvider;

import com.example.demomk.Interface.OnDialogButtonClickListener;

import com.example.demomk.ViewModel.MeasurementViewModel;
import com.example.demomk.databinding.DialogCustomBinding;
import com.example.demomk.entity.Measurement;

import java.util.ArrayList;
import java.util.List;

public class CustomDialog extends Dialog {
    private OnDialogButtonClickListener listener;
    private  DialogCustomBinding binding;
    private EditText startInput,endInput;
    private String message;
    private  FragmentActivity fragmentActivity;
    private int end_page;
    private MeasurementViewModel  viewModel;
    public CustomDialog(@NonNull Context context, @Nullable OnDialogButtonClickListener listener,int end_page,String message) {
        super(context);
        this.listener = listener;
        this.message = message;
        initView();
        create(end_page);
    }
    public CustomDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);
    }
    //详情数据页面
    public CustomDialog(@NonNull Context context, @Nullable OnDialogButtonClickListener listener,int start_print ,int end_print, int Ids,String message) {
        super(context);
        this.listener = listener;
        this.message = message;
        initView();
        createPrint(Ids,start_print,end_print);
    }

    private void initView() {
        // 设置自定义布局
        binding = DialogCustomBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        startInput = binding.startInput;
        endInput = binding.endInput;

        // 设置点击外部可取消
        setCancelable(true);//用户点击返回键时
        setCanceledOnTouchOutside(false);//点击对话框外部区域

        // 设置窗口属性
        Window window = getWindow();
        if (window != null) {
            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

            // 关键修改：添加以下标志
            // 获取屏幕宽度
            DisplayMetrics metrics = new DisplayMetrics();
            window.getWindowManager().getDefaultDisplay().getMetrics(metrics);
            int screenWidth = metrics.widthPixels;

            // 设置对话框宽度为屏幕宽度的90%
            WindowManager.LayoutParams params = window.getAttributes();
            params.width = (int) (screenWidth * 0.9);
            params.height = WindowManager.LayoutParams.WRAP_CONTENT;
            params.dimAmount = 0.2f;
            window.setAttributes(params);
        }
        //点击关闭按钮
        binding.ivClose.setOnClickListener(v -> {
            dismiss();
        });
    }

    private void createPrint(int Ids,int start_print,  int end_print){

        binding.tvTitle.setText(message);


        startInput.setText(String.valueOf(start_print));
        endInput.setText(String.valueOf(end_print));

        // 添加输入过滤器（可选）
        InputFilter rangeFilter = (source, start, end, dest, dstart, dend) -> {
            try {
                int input = Integer.parseInt(dest.toString() + source.toString());
                if (input >= 0 && input <= end_print) return null;
            } catch (NumberFormatException e) {
                // 非法输入不接受
            }
            return "";
        };

        startInput.setFilters(new InputFilter[]{rangeFilter});
        endInput.setFilters(new InputFilter[]{rangeFilter});


        binding.btnConfirm.setOnClickListener(v -> {
            String startValue = startInput.getText().toString().trim();
            String endValue = endInput.getText().toString().trim();



            if(TextUtils.isEmpty(startValue) || TextUtils.isEmpty(endValue)){
                Toast.makeText(getContext(), "输入框不能为空", Toast.LENGTH_SHORT).show();
                return;
            }

            int start_page, endPage;
            try {
                start_page = Integer.parseInt(startValue);
                endPage = Integer.parseInt(endValue);
            } catch (NumberFormatException e) {
                Toast.makeText(getContext(), "请输入有效的数字", Toast.LENGTH_SHORT).show();
                return;
            }

            if(start_page> endPage || start_page == 0){
                Toast.makeText(getContext(), "请输入合规的范围", Toast.LENGTH_SHORT).show();
                return;
            }
            // 确认按钮点击事件
            if (listener != null) {
                listener.onConfirm(start_page, Ids);
            }
            dismiss();
        });
    }

    private void create(int end_page){
        binding.tvTitle.setText(message);
        startInput.setText("1");
        endInput.setText(String.valueOf(end_page));


        // 添加输入过滤器（可选）
        InputFilter rangeFilter = (source, start, end, dest, dstart, dend) -> {
            try {
                int input = Integer.parseInt(dest.toString() + source.toString());
                if (input >= 0 && input <= end_page) return null;
            } catch (NumberFormatException e) {
                // 非法输入不接受
            }
            return "";
        };

        startInput.setFilters(new InputFilter[]{rangeFilter});
        endInput.setFilters(new InputFilter[]{rangeFilter});


        binding.btnConfirm.setOnClickListener(v -> {
            String startValue = startInput.getText().toString().trim();
            String endValue = endInput.getText().toString().trim();



            if(TextUtils.isEmpty(startValue) || TextUtils.isEmpty(endValue)){
                Toast.makeText(getContext(), "输入框不能为空", Toast.LENGTH_SHORT).show();
                return;
            }

            int start_page, endPage;
            try {
                start_page = Integer.parseInt(startValue);
                endPage = Integer.parseInt(endValue);
            } catch (NumberFormatException e) {
                Toast.makeText(getContext(), "请输入有效的数字", Toast.LENGTH_SHORT).show();
                return;
            }

            if(start_page> endPage || start_page == 0){
                Toast.makeText(getContext(), "请输入合规的范围", Toast.LENGTH_SHORT).show();
                return;
            }
            // 确认按钮点击事件
            if (listener != null) {
                listener.onConfirm(start_page, endPage);
            }
            dismiss();
        });
    }
}
